#include "YaoReader.h"

YaoReader::YaoReader()
{
    formatContext = avformat_alloc_context();
}

YaoReader::~YaoReader()
{
    if(formatContext != nullptr){
        avformat_free_context(formatContext);
        formatContext = nullptr;
    }
}

int YaoReader::Open(std::string _path)
{
    if(formatContext == nullptr){
        return -1;
    }
    path = _path;
    int ret = avformat_open_input(&formatContext, path.c_str(), nullptr, nullptr);
    if(ret != 0){
        printf("avformat_open_input fail:%d\n", ret);
    }

    if(!ret){
        ret = avformat_find_stream_info(formatContext, nullptr);
        if(ret < 0){
            printf("avformat_find_stream_info fail \n");
        }
    }

    return ret;
}

int YaoReader::Close()
{
    if(formatContext == nullptr){
        return -1;
    }
    avformat_close_input(&formatContext);
    return 0;
}

int YaoReader::Read(YaoPacket * packet)
{
    if(formatContext == nullptr){
        return -1;
    }
    return av_read_frame(formatContext, packet->avPacket);
}

int YaoReader::GetStreamIndex(enum AVMediaType type)
{
    if(formatContext == nullptr){
        return -1;
    }
    return av_find_best_stream(formatContext, type, -1, -1, nullptr, 0);
}

int YaoReader::GetStream(YaoStream * stream, int streamIndex)
{
    AVStream * avStream = formatContext->streams[streamIndex];
    int ret = avcodec_parameters_copy(stream->avCodecParameters, avStream->codecpar);
    if(ret < 0){
        printf("avcodec_parameters_copy fail ! \n");
    }
    stream->index = avStream->index;
    return ret;
}
